const api = require('../../utils/api.js');
const app = getApp();

Page({
  data: {
    name: '',
    mobile: '',
    address: '',
    longitude: '',
    latitude: '',
    pic_url: '',
    cover_url: '',
    rules: '',
    category: '',
    typename: '',
    read: '',
    review_status: '',
    storeArr: [],
    theme: app.themeData,
    showprotocol: false,
    abnorData: {
      imgSrc: '/common/static/images/abnor-02.png',
      text: '还未添加入驻协议',
    },
    custPicList:[],
    abnorData1: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '该功能已下架，暂不可用！',
    },
    isAuditMode: true,
  },

  onLoad(options) {
    let that = this;
    this.loadStoreType();
    this.loadStoreSetting();
    app.loadShopSetting().then(res => {
      that.setData({
        check_mobile: res.check_mobile,
      });
    });
    app.loadCurrencyUnit().then(res => {
      that.setData({
        currency: res.currency,
      });
    });
  },

  onShow() {
    let resPic =
      wx.getStorageSync('resPic') && JSON.parse(wx.getStorageSync('resPic'));
    let usetype = wx.getStorageSync('usetype') || '';
    if (usetype === 'logo') {
    if (resPic) {
      this.setData({
        pic_url: resPic.url,
      });
    }
    } else if (usetype === 'thumb') {
      if (resPic) {
        this.setData({
          cover_url: resPic.url,
        });
      }
    } else if (usetype === 'custPic') {
      if (resPic) {
        let pics = this.data.custPicList;
        pics.push(resPic.url);
        this.setData({
          custPicList: pics,
        });
      }
    }
  },

  onHide() {
    wx.removeStorageSync('resPic');
    wx.removeStorageSync('usetype');
  },

  onUnload() {
    wx.removeStorageSync('resPic');
    wx.removeStorageSync('usetype');
  },

  loadStoreType() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.storecate,
      success: res => {
        if (res.code === 0) {
          wx.setNavigationBarTitle({
            title: '申请入驻',
          })
          that.setData({
            storeArr: res.data.list,
          });
        } else if (res.code === 10001) {
          that.setData({
            isAuditMode: false,
          })
        }
      },
    });
  },

  loadStoreSetting() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.storeapply,
      method: 'GET',
      success: function (res) {
        if (res.code === 0) {
          let {
            name,
            mobile,
            address,
            latitude,
            longitude,
            pic_url,
            cover_url,
            review_status,
          } = res.data.shop;
          that.setData({
            rules: res.data.settle.entry_rules,
            name,
            mobile,
            address,
            latitude,
            longitude,
            pic_url,
            cover_url,
            review_status,
            identify_name: res.data.settle.identify_name,
            custPicList: res.data.shop.identify_pic || [],
          });
        }  
      },
    });
  },

  chooseStoreType(e) {
    let list = this.data.storeArr;
    let idx = e.detail.value;
    this.setData({
      typename: list[idx].name,
      category: list[idx].id,
    });
  },

  chooseAddr() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.chooseLocation({
            success: function (res) {
              that.setData({
                address: res.address,
                latitude: res.latitude,
                longitude: res.longitude,
              });
            },
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          wx.chooseLocation({
            success: function (res) {
              that.setData({
                address: res.address,
                latitude: res.latitude,
                longitude: res.longitude,
              });
            },
          });
        }
      },
    });
  },

  upLoadImage(e) {
    let _type = e.currentTarget.dataset.type;
    if (_type === 'logo') {
      this.chooseImage('square', 'logo');
    } else if (_type === 'thumb') {
      this.chooseImage('cover', 'thumb');
    }
  },

  chooseImage(sceneName, usetype) {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths[0];
        let url = 'utility/file/upload';
        if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
          url = app.util.url(url, { type: 'image', thumb: '0' });
        }
        wx.setStorage({
          key: 'uploadUrl',
          data: url,
        });
        wx.navigateTo({
          url: `/common/component/cropper/cropper?sceneName=${sceneName}&usetype=${usetype}&src=${tempFilePaths}`,
        });
      },
    });
  },

  customizePics() {
    let list = this.data.custPicList || [];
    let len = list.length;
    if (len < 6) {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          let src = res.tempFilePaths[0];
          let sceneName = 'square';
          let usetype = 'custPic';
          let url = 'utility/file/upload';
          if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
            url = app.util.url(url, { type: 'image', thumb: '0' });
          }
          wx.setStorage({
            key: 'uploadUrl',
            data: url,
          });
          wx.navigateTo({
            url: `/common/component/cropper/cropper?sceneName=${sceneName}&src=${src}&usetype=${usetype}`,
          });
        },
      });
    } else {
      wx.showToast({
        title: '最多只能上传6张商品图片',
        icon: 'none',
      });
    }
  },

  delPicItem(e) {
    let index = e.currentTarget.dataset.idx;
    let piclist = this.data.custPicList;
    piclist.splice(index, 1);
    this.setData({
      custPicList: piclist,
    });
  },

  showProtocol() {
    this.setData({
      showprotocol: true,
    });
  },

  hideProtocol() {
    this.setData({
      read: false,
      showprotocol: false,
    });
  },

  agreeProtocol() {
    this.setData({
      read: true,
      showprotocol: false,
    });
  },

  checkedProtocol(e) {
    let val = e.detail.value;
      this.setData({
      read: val[0] === 'read',
      });
  },

  applySubmit(e) {
    let that = this;
    let { name, mobile, address } = e.detail.value;
    let {
      longitude,
      latitude,
      pic_url,
      cover_url,
      check_mobile,
      category,
      custPicList,
      identify_name,
    } = that.data;
    if (!name.trim()) {
      wx.showToast({
        title: '请填写店铺名称',
        icon: 'none',
      });
      return;
    }
    if (!mobile.trim()) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none',
      });
      return;
    }
    if (Number(check_mobile) === 1) {
      if (that.data.currency === 'CNY') {
        if (
          !app.util.phoneExp.mobile.test(mobile) &&
          !app.util.phoneExp.landline.test(mobile)
        ) {
      wx.showToast({
        title: '联系电话格式不正确',
        icon: 'none',
      });
      return;
        }
      } else {
        if (!app.util.phoneExp.canadaPhone.test(mobile)) {
          wx.showToast({
            title: '联系电话格式不正确',
            icon: 'none',
          });
          return;
        }
      }
    }
    if (!category) {
      wx.showToast({
        title: '请选择门店分类',
        icon: 'none',
      });
      return;
    }
    if (!address) {
      wx.showToast({
        title: '请选择店铺地址',
        icon: 'none',
      });
      return;
    }
    if (!pic_url) {
      wx.showToast({
        title: '请上传店铺logo图',
        icon: 'none',
      });
      return;
    }
    if (!cover_url) {
      wx.showToast({
        title: '请上传店铺封面图',
        icon: 'none',
      });
      return;
    }
    if (!custPicList) {
      wx.showToast({
        title: '请上传' + identify_name,
        icon: 'none',
      });
      return;
    }
    if (!that.data.read) {
      wx.showToast({
        title: '请阅读‘入驻协议’并同意',
        icon: 'none',
      });
      return;
    }
    app.ws_micro_shoprequest({
      url: api.default.storeapply,
      method: 'POST',
      data: {
        name,
        mobile,
        address,
        latitude,
        longitude,
        pic_url,
        cover_url,
        category,
        identify_pic: custPicList,
      },
      success: function (res) {
        if (res.code === 0) {
          wx.showModal({
            title: '提示',
            content: '申请成功',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                wx.navigateBack();
              }
            },
          });
        } else {
          wx.showToast({
            title: '申请失败',
            icon: 'none',
          });
        }
      },
    });
  },
});
